<?php

namespace mongrove;

use MongoDate;

/**
 *
 * The DateField encapsulates date/time properties in Mongo documents.
 * In normal usage this property will be represented as an integer, Unix timestamp.
 *
 * @author Gido Hakvoort <gido@hakvoort.it>
 * @author Michiel Hakvoort <michiel@hakvoort.it>
 *
 */
class DateField extends SimpleField {

    /**
     * Specify a DateField with a default value
     *
     * @param int $default
     */
    public function __construct($default = null) {
    	parent :: __construct();

    	if($default !== null) {
            $this->setValue($default);
    	}
    }

    /**
     * (non-PHPdoc)
     * @see src/mongrove.SimpleField::getValue()
     */
    public function getValue() {
        if($this->value === null) {
            return null;
        }

        return $this->value->sec;
    }

    /**
     * (non-PHPdoc)
     * @see src/mongrove.SimpleField::setValueImpl()
     */
    protected function setValueImpl($value) {
        if(filter_var($value, FILTER_VALIDATE_INT) === false) {
            throw new \Exception("{$value} is not a valid value for this field.");
        }

        $value = new MongoDate($value);

        if($this->value === $value) {
    		return false;
    	}

    	$this->value = $value;

    	return true;
    }

    /**
     * Rewrite set integers to MongoDate objects
     *
     * @see \mongrove\SimpleField :: rewriteQuery()
     */
    public function rewriteQuery(array $partialQuery) {
        // TODO handle arrays of values
        foreach($partialQuery as $operator => $value) {
            $partialQuery[$operator] = new MongoDate($value);
        }

        return $partialQuery;
    }
}